package com.xyc.petmallsystem.controller;

import com.xyc.petmallsystem.pojo.Admin;
import com.xyc.petmallsystem.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Joel
 * @date 2021/11/26
 */

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminRepository adminRepository;

    /*
    查询所有
     */
    @RequestMapping("/find")
    public List<Admin> find() {
        return adminRepository.findAll();
    }

    /*
       登录判断 用户名和密码
        */
    @PostMapping("/login")
    public String login(@RequestBody Admin admin) {
        System.out.println("登录要判断的用户:" + admin);

        Admin result = adminRepository.login(admin.getName(), admin.getPassword());
        if (result != null) {
            if (result.getName().equals(admin.getName()) && result.getPassword().equals(admin.getPassword())) {
                return "success";
            } else {
                return "error";
            }
        }
        return "error";
    }

    /*
    修改密码
     */
    @GetMapping("/change/{name}/{pwd0}/{pwd1}/{pwd2}")
    public String change(@PathVariable String name, @PathVariable String pwd0, @PathVariable String pwd1, @PathVariable String pwd2) {

        Admin admin = adminRepository.findByName(name);
        //判断原密码正确性
        String password = admin.getPassword();
        if (!pwd0.equals(password)) {
            System.out.println("原密码错误");
            return "Original password error";
        }
        if (!pwd1.equals(pwd2)) {
            System.out.println("密码不一致");
            return "Inconsistent passwords";
        }
        //符合条件，修改密码
        admin.setPassword(pwd1);
        adminRepository.save(admin);
        System.out.println("修改成功，新密码为:"+admin.getPassword());
        return "success";
    }
}
